package com.mp.fileupload.controller;
import com.mp.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

/**
 *  文件上传
 * @author: notejava
 * @date:   2019 11 9
 */
@RestController
public class FileController {
    //文件真实路径
    @Value("${file.really-path}")
    public  String reallyPath;
    //文件虚拟路径
    @Value("${file.virtual-path}")
    public  String virtualPath;
    //文件url
    @Value("${file.file-url}")
    public String fileUrl;

    /**
    * 文件上传
    *@param:
    *@return:  Result
    */
    @PostMapping("/file")
    public Result fileUpload(@RequestParam("file") MultipartFile file) throws Exception{
        Map map=new HashMap<>();
        //设置文件名称，使用uuid
        String fileName = UUID.randomUUID().toString();
        //得到原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //图片保存
        File newFile = new File( reallyPath+"/" + fileName + suffix);
        file.transferTo(newFile);
        //文件访问地址
        String url=fileUrl+virtualPath+"/";
        map.put("url",url);
        map.put("fileName",fileName + suffix);
        map.put("suffix",suffix);
        return Result.success(map);
    }

}
